"""
Development setup script for the 360 Image Extractor addon.
This script provides utilities for setting up a development environment,
including creating symbolic links and auto-reload functionality.
"""

import os
import sys
try:
    import bpy
    import addon_utils
    # Flag to indicate if we're running within Blender
    IN_BLENDER = True
except ImportError:
    # We're running outside of Blender
    bpy = None
    addon_utils = None
    IN_BLENDER = False
import subprocess
import platform
import shutil
from pathlib import Path

def get_blender_addons_path() -> str:
    """
    Automatically detect Blender's addons path based on the operating system.
    """
    system = platform.system()
    
    if system == "Windows":
        # Common paths for Windows
        paths_to_check = [
            os.path.expandvars("%APPDATA%\\Blender Foundation\\Blender\\4.5\\scripts\\addons"),
            os.path.expandvars("%USERPROFILE%\\AppData\\Roaming\\Blender Foundation\\Blender\\4.5\\scripts\\addons"),
        ]
    elif system == "Darwin":  # macOS
        paths_to_check = [
            os.path.expanduser("~/Library/Application Support/Blender/4.5/scripts/addons"),
        ]
    else:  # Linux and others
        paths_to_check = [
            os.path.expanduser("~/.config/blender/4.5/scripts/addons"),
            os.path.expanduser("~/.blender/4.5/scripts/addons"),
        ]
    
    # Check if any of these paths exist
    for path in paths_to_check:
        if os.path.exists(os.path.dirname(path)):
            # Create the addons directory if it doesn't exist
            os.makedirs(path, exist_ok=True)
            return path
    
    # If none of the standard paths exist, return the first one as default
    return paths_to_check[0]

def create_dev_link() -> bool:
    """
    Create a symbolic link from the development directory to Blender's addons directory.
    """
    try:
        # Get the development directory (parent of current directory)
        current_dir = os.path.dirname(os.path.abspath(__file__))
        dev_dir = os.path.dirname(current_dir)
        addon_name = "360ImageExtractor"
        
        # Get Blender's addons path
        addons_path = get_blender_addons_path()
        
        if not os.path.exists(addons_path):
            print(f"Blender addons path does not exist: {addons_path}")
            return False
        
        # Path for the symbolic link
        link_path = os.path.join(addons_path, addon_name)
        target_path = os.path.join(dev_dir, addon_name)
        
        # Remove existing link or file if it exists
        if os.path.exists(link_path):
            if platform.system() == "Windows":
                # On Windows, check if it's a junction point
                try:
                    # Attempt to delete as a junction point
                    subprocess.run(["cmd", "/c", "rmdir", link_path], check=True, capture_output=True)
                except subprocess.CalledProcessError:
                    # If that fails, try as a regular file/directory
                    if os.path.isfile(link_path):
                        os.remove(link_path)
                    elif os.path.isdir(link_path):
                        shutil.rmtree(link_path)
            else:
                # On Unix-like systems
                if os.path.islink(link_path) or os.path.isfile(link_path):
                    os.remove(link_path)
                elif os.path.isdir(link_path):
                    shutil.rmtree(link_path)
        
        # Create symbolic link
        if platform.system() == "Windows":
            # On Windows, use junction points for directories
            result = subprocess.run([
                "cmd", "/c", "mklink", "/J", 
                link_path,
                target_path
            ], capture_output=True, text=True, shell=True)
            
            if result.returncode != 0:
                print(f"Failed to create symbolic link: {result.stderr}")
                return False
        else:
            # On Unix-like systems, use os.symlink
            os.symlink(target_path, link_path)
        
        print(f"Created symbolic link from {target_path} to {link_path}")
        return True
        
    except Exception as e:
        print(f"Error creating symbolic link: {e}")
        return False

def reload_addon_modules():
    """
    Reload all modules of the addon for development.
    """
    # Check if we're running within Blender
    if not IN_BLENDER:
        print("Reload functionality only available within Blender")
        return False
    
    addon_name = "360ImageExtractor"
    
    try:
        # Reload the addon
        addon_utils.modules_refresh()
        bpy.ops.preferences.addon_disable(module=addon_name)
        bpy.ops.preferences.addon_enable(module=addon_name)
        print(f"Reloaded addon: {addon_name}")
        return True
    except Exception as e:
        print(f"Failed to reload addon {addon_name}: {e}")
        return False

def main():
    """
    Main function to provide a menu for development setup options.
    """
    print("360 Image Extractor Development Setup")
    print("=====================================")
    print("")
    print("1. Create symbolic link to Blender addons directory")
    print("2. Reload addon modules (requires Blender to be running)")
    print("3. Exit")
    print("")
    
    choice = input("Select an option (1-3): ").strip()
    
    if choice == "1":
        if create_dev_link():
            print("\nSymbolic link created successfully!")
            print("You can now enable the addon in Blender.")
        else:
            print("\nFailed to create symbolic link.")
    elif choice == "2":
        if IN_BLENDER:
            if reload_addon_modules():
                print("\nAddon reloaded successfully!")
            else:
                print("\nFailed to reload addon.")
        else:
            print("\nReload functionality only available within Blender.")
            print("Please run this script from within Blender's Python console or as an addon.")
    elif choice == "3":
        print("Exiting...")
    else:
        print("Invalid option selected.")

if __name__ == "__main__":
    main()